import { RouteRecordName, createRouter, createWebHashHistory } from 'vue-router'
import Login from '@admin/views/login/IndexView.vue'
import MainView from '@admin/views/MainView.vue'
import HomeView from '@admin/views/home/IndexView.vue'
import { getToken } from '~/utils'
import subRoutes from './routes'

const whiteRouteNames: RouteRecordName[] = [
    'Login'
]

const gloabRoutes = [
    { path: '/login', name: 'Login', component: Login }
]

const routes = [
    ...gloabRoutes,
    {
        path: '/',
        redirect: '/home'
    },
    {
        path: '/',
        name: 'Main',
        component: MainView,
        children: [
            {
                path: '/home',
                name: 'Home',
                component: HomeView,
            },
            ...subRoutes
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})


router.beforeEach((_to, _from, next) => {
    if (whiteRouteNames.includes(_to.name as RouteRecordName)) {
        next()
    } else if (getToken()) {
        next()
    } else {
        next({
            path: '/login'
        })
    }
})

export default router
